﻿using MediatR;
using Sowrk03_28.Repository;
using Swork03_28.Api.Application.Commands.SlaughterCommand;
using Swork03_28.Domain.TraceableInfos;
using Swork03_28.Services.Impls;

namespace Swork03_28.Api.Application.CommandHandlers.SlaughterCommandHandler
{
    /// <summary>
    /// 添加屠宰相关资质
    /// </summary>
    public class CertificationCreateCommandHandler : IRequestHandler<CertificationCreateCommand, int>
    {
        private readonly IRepository<Slaughter> repository;

        public CertificationCreateCommandHandler(IRepository<Slaughter> repository)
        {
            this.repository = repository;
        }

        public async Task<int> Handle(CertificationCreateCommand request, CancellationToken cancellationToken)
        {
            var count = 0;
            var info = await repository.GetValues(x => x.BatchId == request.BatchId);
            var res = info.FirstOrDefault();
            if (res != null)
            {
                res.Certification = (res.Certification + "," + request.Imgs).TrimStart(",".ToCharArray()).TrimEnd(",".ToCharArray());
                count += await repository.UpdateAsync(res);
            }
            else
            {
                var imgs = ("," + request.Imgs).TrimStart(",".ToCharArray()).TrimEnd(",".ToCharArray());
                count += await repository.CreateAsync(new Slaughter()
                {
                    BatchId = request.BatchId,
                    CreateBy = "张三",
                    CreateDate = DateTime.Now,
                    Certification = imgs,
                     BeginData=null,
                      FinishData=null
                });
            }
            return count;
        }
    }
}
